package demo1;
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-02
 * Time: 12:46
 */
public class Thread_Safe_Two_DoubleLock_ {
    public static void main1(String[] args) {
        Object object = new Object();
        Thread thread = new Thread(()->{
            synchronized (object){
                synchronized (object){
                    System.out.println("Hello thread");
                }
            }
        });
        thread.start();
    }
    //两个线程两把锁,并且陷入了循环等待,导致死锁
    public static void main2(String[] args) {
        Object objectA = new Object();
        Object objectB = new Object();
        Thread threadA = new Thread(()->{
            synchronized (objectA){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //A线程已经获取了A锁，再尝试获取B锁
                synchronized (objectB){
                    System.out.println("Hello threadA");
                }
            }
        });
        Thread threadB = new Thread(()->{
            synchronized (objectB){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //B线程已经获取了B锁，再尝试获取A锁
                synchronized (objectA){
                    System.out.println("Hello threadB");
                }
            }
        });
        threadA.start();
        threadB.start();
    }
    //两个线程两把锁,没有陷入循环等待,破解了死锁
    public static void main(String[] args) {
        Object objectA = new Object();
        Object objectB = new Object();
        Thread threadA = new Thread(()->{
            synchronized (objectA){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //A线程已经获取了A锁，再尝试获取B锁
                synchronized (objectB){
                    System.out.println("Hello threadA");
                }
            }
        });
        Thread threadB = new Thread(()->{
            synchronized (objectA){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //B线程已经获取了B锁，再尝试获取A锁
                synchronized (objectB){
                    System.out.println("Hello threadB");
                }
            }
        });
        threadA.start();
        threadB.start();
    }
}

















